layui.define(['laytpl',"jquery","table"], function(exports){
  var $ = layui.jquery;
  var laytpl = layui.laytpl;
  var table = layui.table;
  var defaultConfig = {
    idKey:"id",
    parentIdKey:"parentId",
    id:"id",
    childrenKey:"children",
    titleKey:"name",
    titleLabel:"名称",
    ele:"#tableView",
    url:"/cmf_admin_menu.json",
    cols:[
      
    ]
  };
  
  var getTpl = $("#demo").html();
  var treeGrid = {
    config:{},
    data:[],
	  render:function(config){
      var $this = this;
      $("body").append(' <style>.tree-row-hidden{display: none;}</style>');
      config = $.extend({},defaultConfig, config);
      this.config = $.extend({},this.config,config);
      
      /*this.config.cols.unshift(
        {
        field: this.config.titleKey, 
        title: this.config.titleLabel,
        templet:function(d){
        return '<span class="indenter" style="padding-left:'+d.level*10+'px"></span><i class="layui-icon layui-icon-triangle-r tree-icon"></i>'+d[config.titleKey];
        }
      });*/
      var template = '<table class="layui-table">';   
      template+='<thead>\n\r';   
      template+='<tr>\n\r';
      template+='<th>\n\r';
      template+=this.config.titleLabel;
      template+='</th>\n\r';
	  template+=this.renderHead();
      template+="</tr>\n\r";
      template+="</thead>\n\r";
      template+="<tbody>\n\r";
      template+="{{d}}";
      template+='</tbody>\n\r';
      template+='</table>\n\r';

      if(config.url) {
        $.ajax({
          url:config.url,
          success:function(data){
          
            var d = $this.preorder($this.getTree(data.data),1);
            this.data = d;
            laytpl(template).render($this.renderRow($this.getTree(data.data),1), function(html){
             $($this.config.ele).html(html);;
            });
            // table.render({
            //   elem: config.ele,
            //   data: d,
            //   cols: new Array(config.cols),
            //   id:config.id,
            //   limit: d.length
            // });
              $.each($(config.ele).next("div").find("tbody").children("tr"),function(index,item){
                $(item).attr("data-tt-id",d[index][config.idKey]);
                $(item).attr("data-tt-parent-id",d[index][config.parentIdKey]);
                $(item).attr("data-tt-level",d[index].level);
                $(item).attr("data-tt-leaf",d[index].leaf);
              })
              $("tr[data-tt-level]").addClass("tree-row-hidden");
              $("tr[data-tt-level=1]").removeClass("tree-row-hidden");
              $("tr[data-tt-leaf=true]").find(".tree-icon").removeClass("layui-icon-triangle-r").addClass("layui-icon-file");
              $(".tree-icon").on("click",function(e){
              if($(this).hasClass("layui-icon-triangle-r")){
                $(this).removeClass("layui-icon-triangle-r").addClass("layui-icon-triangle-d");
                var id = $(this).parents("tr").eq(0).data("tt-id");
                var parentId = $(this).parents("tr").eq(0).data("tt-parent-id");
                $("tr[data-tt-parent-id="+id+"]").removeClass("tree-row-hidden");
              } else {
                $(this).removeClass("layui-icon-triangle-d").addClass("layui-icon-triangle-r");
                var id = $(this).parents("tr").eq(0).data("tt-id");
                var parentId = $(this).parents("tr").eq(0).data("tt-parent-id");
                $this.hiddenChildren(id);
              }
              })
          }
        })
        
      }
    },
	renderRow: function(datas,level){
	  if(datas&&datas.length){
		var str = '';
		for(var i=0,len=datas.length;i<len;i++){
		  var item = datas[i];
		  var leaf = !(item.children&&item.children.length);
		  str+='<tr data-tt-id="'+item.id+'" data-tt-parent-id="'+item[this.config.parentIdKey]+'" data-tt-level="'+level+'" data-tt-leaf="'+leaf+'">';
		  str+='<td><span class="indenter" style="padding-left:'+level*10+'px"></span><i class="layui-icon layui-icon-triangle-r tree-icon"></i>'+item.name+'</td>';
		  str+=this.renderCol(item);
		  str+=this.renderRow(item.children,level+1);
		}
		return str;
	  } else {
		return "";
	  }
	},
	renderHead(){
		var str = "";
		for(var i=0,len=this.config.cols.length;i<len;i++) {
			var item = this.config.cols[i];
			str+="<th>"+item.title+"</th>";
		}
		return str;
	},
	renderCol(data){
		var str = "";
		for(var i=0,len=this.config.cols.length;i<len;i++) {
			var item = this.config.cols[i];
			if( typeof item.templet === "function"){
				str+="<td>"+item.templet(item)+"</td>";
			} else {
				str+="<td>"+data[item.field]+"</td>";
			}
		}
		return str;
	},
    hiddenChildren: function(id) {
      var $this = this;
      $("tr[data-tt-parent-id="+id+"]").addClass("tree-row-hidden");
      $.each($("tr[data-tt-parent-id="+id+"]"),function(index,item){
      var iid = $(item).data("tt-id");
        $("tr[data-tt-id="+iid+"][data-tt-leaf=false]").find(".tree-icon").removeClass("layui-icon-triangle-d").addClass("layui-icon-triangle-r");
        $this.hiddenChildren($(item).data("tt-id"));
      })
    },
    getTree: function(node) {
      var root = [];
      for (var i = 0; i < node.length; i++) {
        // node[i].title = node[i].name;
        if (Number(node[i][this.config.parentIdKey]) <= 0) {
          root.push(node[i]);
        }
      }
      return this.buildTree(node, root);
    },
     buildTree: function(node, root) {
      for (var i = 0; i < root.length; i++) {
        var children = [];
        for (var k = 0; k < node.length; k++) {
          if (node[k][this.config.parentIdKey] == root[i][this.config.idKey]) {
            children.push(node[k]);
          }
        }
        if (children.length != 0) {
          root[i][this.config.childrenKey] = children;
          this.buildTree(node, children);
        }
      }
      return root;
    },
     preorder: function(tree,level){
      var array = [];
          for (var i = 0; i < tree.length; i++) {
            tree[i].level = level;
            if (tree[i][this.config.childrenKey] != null) {
              tree[i].leaf=false;
              array.push(tree[i]);
              array = array.concat(this.preorder(tree[i][this.config.childrenKey], level + 1));
            } else {
              tree[i].leaf=true;
              array.push(tree[i]);
            }
             tree[i][this.config.childrenKey]=[];
          }
      return array;
    }
  }
  var Node = (function(){
    function Node(row, tree, settings){
      var parentId = '';
      this.row = row;
      this.tree = tree;
      this.settings = settings;
    }
    Node.prototype.render=function(){

    }
    return Node;
  })();
  
  exports('treeGrid', treeGrid);
});